<template>
  <div class="container-fluid">
    <!-- 顶部导航栏 -->
    <header class="col-md-12 bg-primary text-white p-3">
      <div class="d-flex align-items-center w-100">
        <div>
          <h1>停车场管理系统</h1>
        </div>
        <div class="d-flex items-center" style="margin-left: auto;">
          <span class="mr-4">{{ username }}</span>
          <router-link to="/" class="btn btn-light mr-2">返回首页</router-link>
          <button @click="logout" class="btn btn-light">退出</button>
        </div>
      </div>
    </header>

    <!-- 主内容区域 -->
    <main class="col-md-12 mt-4">
      <div class="card">
        <div class="card-header bg-secondary text-white">
          <h2 class="text-center">用户管理</h2>
        </div>
        <div class="card-body">
          <div class="mb-4 d-flex justify-content-between">
            <div class="d-flex">
              <input 
                type="text" 
                v-model="searchKeyword"
                placeholder="搜索用户名" 
                class="form-control mr-2"
                style="width: 200px;"
              >
              <button @click="searchUser" class="btn btn-info">搜索</button>
            </div>
            <div>
              <button @click="addUser" class="btn btn-primary">添加用户</button>
            </div>
          </div>
          
          <div v-if="loading" class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
              <span class="sr-only">加载中...</span>
            </div>
            <p class="mt-2">正在加载用户数据...</p>
          </div>
          <table v-else class="table table-bordered">
            <thead>
              <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>姓名</th>
                <th>手机号</th>
                <th>邮箱</th>
                <th>角色</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="userList.length === 0">
                <td colspan="8" class="text-center">暂无用户数据</td>
              </tr>
              <tr v-else v-for="user in userList" :key="user.id">
                <td>{{ user.id }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.name }}</td>
                <td>{{ user.phone }}</td>
                <td>{{ user.email }}</td>
                <td>{{ user.roleName }}</td>
                <td>
                  <span :class="{
                    'text-success': user.status === 1,
                    'text-danger': user.status === 0
                  }">
                    {{ user.status === 1 ? '正常' : '禁用' }}
                  </span>
                </td>
                <td>{{ user.formattedCreateAt }}</td>
                <td>
                  <button @click="editUser(user.id)" class="btn btn-info btn-sm mr-2">编辑</button>
                  <button 
                    @click="toggleUserStatus(user.id)" 
                    :class="['btn', 'btn-sm', user.status === 1 ? 'btn-warning' : 'btn-success', 'mr-2']"
                  >
                    {{ user.status === 1 ? '禁用' : '启用' }}
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
          <!-- 分页组件 -->
          <div v-if="!loading && userList.length > 0" class="mt-4 d-flex justify-content-between align-items-center">
            <div class="text-muted">共 {{ total }} 条记录</div>
            <div>
              <button 
                @click="handleCurrentChange(currentPage - 1)"
                :disabled="currentPage === 1 || loading"
                class="btn btn-outline-primary mr-2"
              >
                上一页
              </button>
              <span class="mx-2">{{ currentPage }}/{{ Math.ceil(total / pageSize) || 1 }}</span>
              <button 
                @click="handleCurrentChange(currentPage + 1)"
                :disabled="currentPage >= Math.ceil(total / pageSize) || loading"
                class="btn btn-outline-primary ml-2"
              >
                下一页
              </button>
              <select 
                v-model="pageSize" 
                @change="handleSizeChange(pageSize)"
                class="ml-4 form-control d-inline-block" 
                style="width: auto;"
              >
                <option :value="7">7条/页</option>
                <option :value="10">10条/页</option>
                <option :value="20">20条/页</option>
              </select>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import axios from '../../utils/axios';

export default {
  name: 'UserManageView',
  data() {
    return {
      username: '',
      userList: [],
      searchKeyword: '',
      currentPage: 1,
      pageSize: 7,
      total: 0,
      loading: false
    }
  },
  mounted() {
    this.username = localStorage.getItem('username') || '管理员'
    this.loadUserList()
  },
  methods: {
    logout() {
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('username')
      this.$router.push('/login')
    },
    
    // 角色ID映射为角色名称
    getRoleName(roleId) {
      const roleMap = {
        1: '超级管理员',
        2: '普通操作员',
        3: '财务人员',
        4: '普通用户'
      };
      return roleMap[roleId] || '未知角色';
    },
    
    // 格式化时间为年月日时分秒格式
    formatDateTime(dateTime) {
      if (!dateTime) return '-';
      
      // 处理字符串格式的日期
      let date;
      if (typeof dateTime === 'string') {
        // 尝试解析各种日期格式
        date = new Date(dateTime);
        // 如果解析失败，尝试其他格式
        if (isNaN(date.getTime())) {
          // 处理Thu Sep 18 21:28:53 CST 2025这样的格式
          date = new Date(dateTime.replace('CST ', ''));
        }
      } else if (dateTime instanceof Date) {
        date = dateTime;
      } else {
        // 如果是时间戳
        date = new Date(dateTime);
      }
      
      if (isNaN(date.getTime())) {
        return '-';
      }
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    // 处理用户数据，添加角色名称和格式化时间
    processUserData(userList) {
      return userList.map(user => ({
        ...user,
        roleName: this.getRoleName(user.roleId),
        formattedCreateAt: this.formatDateTime(user.createdAt || user.createAt)
      }));
    },
    
    async loadUserList() {
      this.loading = true;
      try {
        // 使用相对路径，基于axios.js中已配置的baseURL
        const response = await axios.get('/users/page', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            username: this.searchKeyword || undefined
          }
        });
        
        console.log('API响应数据:', response);
        
        // 后端返回的是PageInfo对象，需要从中提取数据
        if (response && response.list) {
          // 如果是PageInfo对象，提取list和total，并处理数据
          this.userList = this.processUserData(response.list);
          this.total = response.total;
          console.log('提取并处理的用户列表:', this.userList);
          console.log('用户列表长度:', this.userList.length);
          if (this.userList.length > 0) {
            console.log('第一个用户的数据:', this.userList[0]);
          }
        } else if (Array.isArray(response)) {
          // 如果直接返回数组，则使用整个数组并处理数据
          this.userList = this.processUserData(response);
          this.total = response.length;
          console.log('直接使用并处理的数组数据:', this.userList);
        } else {
          // 默认情况
          this.userList = [];
          this.total = 0;
          console.log('无数据，使用空列表');
        }
      } catch (error) {
        console.error('加载用户列表失败:', error);
        // 增强错误提示信息，显示具体的错误类型
        if (error.message && error.message.includes('ERR_FAILED')) {
          alert('加载用户列表失败：无法连接到后端服务。请确认端口2509的Maven服务已启动。');
        } else {
          alert('加载用户列表失败：' + (error.message || '未知错误，请重试'));
        }
        
        // 失败时使用模拟数据作为备用
        // 使用更接近后端格式的数据结构作为模拟数据
        this.userList = this.processUserData([
          { id: 1, username: 'admin', name: '管理员', phone: '13800138000', email: 'admin@example.com', roleId: 1, status: 1, createdAt: 'Thu Sep 18 21:28:53 CST 2025' },
          { id: 2, username: 'operator', name: '操作员', phone: '13800138001', email: 'operator@example.com', roleId: 2, status: 1, createdAt: 'Thu Sep 18 21:29:53 CST 2025' },
          { id: 3, username: 'finance', name: '财务', phone: '13800138002', email: 'finance@example.com', roleId: 3, status: 1, createdAt: 'Thu Sep 18 21:30:53 CST 2025' },
          { id: 4, username: 'user1', name: '普通用户', phone: '13800138003', email: 'user1@example.com', roleId: 4, status: 1, createdAt: 'Thu Sep 18 21:31:53 CST 2025' }
        ]);
        this.total = this.userList.length;
      } finally {
        this.loading = false;
      }
    },
    
    // 测试按钮方法
    testButton() {
      console.log('测试按钮被点击');
    },
    
    // 添加用户方法
    addUser() {
      this.$router.push('/system/user/add');
    },
    
    editUser(id) {
      // 编辑用户逻辑
      alert(`编辑用户 ${id}`)
    },
    
    toggleUserStatus(id) {
      // 启用/禁用用户逻辑
      const user = this.userList.find(u => u.id === id)
      if (user) {
        if (confirm(`确定要${user.status === 1 ? '禁用' : '启用'}用户 ${user.username} 吗？`)) {
          user.status = user.status === 1 ? 0 : 1
          alert(`用户 ${user.username} 已${user.status === 1 ? '启用' : '禁用'}`)
        }
      }
    },
    
    resetPassword(id) {
      // 重置密码逻辑
      const user = this.userList.find(u => u.id === id)
      if (user) {
        if (confirm(`确定要重置用户 ${user.username} 的密码吗？`)) {
          alert(`用户 ${user.username} 的密码已重置为默认密码：123456`)
        }
      }
    },
    
    searchUser() {
      // 重置为第一页，然后调用loadUserList进行搜索
      this.currentPage = 1;
      this.loadUserList();
    },
    
    // 分页方法
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadUserList();
    },
    
    handleCurrentChange(current) {
      this.currentPage = current;
      this.loadUserList();
    }
  }
}
</script>

<style >
/* 这里可以添加组件特定的样式 */
</style>